package com.zjj.filmcommentapi.controller;

import com.zjj.filmcommentapi.model.User;
import com.zjj.filmcommentapi.service.UserService;
import com.zjj.filmcommentapi.utils.Result;
import com.zjj.filmcommentapi.utils.annotation.PassToken;
import com.zjj.filmcommentapi.utils.annotation.UserToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@Api(value = "User用户相关", tags = "User用户相关")
public class UserController {
    @Autowired
    private UserService userService;

    @ApiOperation(value = "注册接口", notes = "直接注册")
    @RequestMapping(value = "/reg", produces = {"application/JSON"}, method = RequestMethod.POST)
    private Result reg(@ModelAttribute User user) {
        return userService.reg(user);
    }

    @ApiOperation(value = "登录接口", notes = "直接登录")
    @ApiImplicitParam(name = "User", value = "用户信息", dataType = "User")
    @PassToken
    @RequestMapping(value = "/login", produces = {"application/JSON"}, method = RequestMethod.POST)
    private Result login(@ModelAttribute User user) {
        return userService.login(user);
    }
    @ApiOperation(value = "退出登录", notes = "退出")
    @PassToken
    @RequestMapping(value = "/logout", produces = {"application/JSON"}, method = RequestMethod.POST)
    private Result logout(HttpServletRequest request){
        String cookie = request.getHeader("Cookie");
        String token = cookie.substring(cookie.indexOf("sessionId=")+10);// 从http请求头中取出token
        if (userService.logout(token)){
            return Result.success("退出成功",200);
        }else {
            return Result.error("退出异常",500);
        }
    }
    @ApiOperation(value = "得到个人信息", notes = "个人信息")
    @RequestMapping(value = "/getuserinfo", produces = {"application/JSON"}, method = RequestMethod.POST)
    private  Result getUserInfo(HttpServletRequest request){
        String cookie = request.getHeader("Cookie");
        String token = cookie.substring(cookie.indexOf("sessionId=")+10);// 从http请求头中取出token
        return Result.success(userService.getUserInfo(token));
    }
    @UserToken
    @RequestMapping(value = "/userlist", method = RequestMethod.GET)
    private Result getUserList() {
        return userService.getUserList();
    }

    @RequestMapping(value = "/updatestate", produces = {"application/JSON"}, method = RequestMethod.POST)
    private Result upadteUserState(@ModelAttribute User user) {
        return userService.updateUser(user);
    }
}
